package com.cobo.fitness.web.calibreapi.routes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cobo.common.core.R;
import com.cobo.fitness.web.calibreapi.entity.Book;
import com.cobo.fitness.web.calibreapi.entity.Library;
import com.cobo.fitness.web.calibreapi.model.BookMeta;
import com.cobo.fitness.web.calibreapi.services.CalibreApi;
import com.cobo.fitness.web.calibreapi.services.IBookService;
import com.cobo.fitness.web.calibreapi.services.LibraryService;
import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/calibre/api")
public class CalibreController {

    @Autowired
    private IBookService bookService;

    @Autowired
    private LibraryService libraryService;

    @GetMapping("/list")
    public R list() {
        CalibreApi.selectBooks();
        return R.ok();
    }

    @GetMapping("/book/list")
    public R<BookMeta> bookItemList(){
        List<Book> books = bookService.list();
        return R.ok(CalibreApi.getBookMeta(books));
    }



    @PostMapping("/book/query")
    public R<List<Book>> queryBooks(@RequestBody SearchQuery query ){
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        query.fillQuery(wrapper);
        List<Book> books = bookService.list(wrapper);
        return R.ok(books);
    }

    @PostMapping("/book/update")
    public R<List<Book>> queryBooks(@RequestBody Book book ){


        bookService.update(null, new LambdaUpdateWrapper<Book>()
                .eq(Book::getId, book.getId())
                .set(Book::getName, book.getName())
                .set(Book::getBookTag, book.getBookTag())
                .set(Book::getBookLang, book.getBookLang())
                .set(Book::getBookRate, book.getBookRate())
                .set(Book::getBookSize, book.getBookSize())
                .set(Book::getAuthor, book.getAuthor())
                .set(Book::getTagCode, book.getTagCode())
                .set(Book::getBookPublish, book.getBookPublish())
        );
        return R.ok();
    }

    @GetMapping("/init")
    public R initLibrary() {
        Library library = libraryService.list().get(0);
        List<Book> books = CalibreApi.initLibrary(library.getLibraryPath());
        bookService.saveBatch(books);
        return R.ok();
    }
}
